// pages/circle/circle.js
import api from "../../config/api";
import { shareOptions } from "../../utils/access";
import request from "../../utils/request";
import { getBarAndTitleHeight, jump,getStorage,setStorage, goBack } from "../../utils/utils";

const app = getApp()
// 引入动画插件
import lottie from './lottie'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 帖子列表
    formShare:false,
    list: [],
    page: 1,
    total: 0,
    isDone: false,
    // 圈子id
    id: null,
    // 详情数据
    info: {},
    //  标签页选中项
    tabIndex: '1',
    //  swiper选中项
    swiperIndex: 0,
    // 类型初始滑动位置
    typeScrollX: 0,
    // 页面滚动高度
    scrollTop: 0,
    // 信号栏高度
    ...getBarAndTitleHeight(),
    // 投票征稿期间展示引导提示
    showTips: false,
    // 页面是否加载完成
    isReady: false,
  },
  // 点赞loading
  loading: false,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options?.inviteData) {
			setStorage('inviteData', options?.inviteData)
			console.log('分享人数据：', options.inviteData)
		}
    this.setData({
      id: options?.id,
      formShare:options?.formShare
    }, () => {
      this.getInfo()
      this.getList(1)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.initAnimate()
    this.modal = this.selectComponent('#modal')
    this.sheet = this.selectComponent('#sheet')
    this.setData({
      isReady: true
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 发布帖子之后刷新页面
    if (this.isFromPublish) {
      this.isFromPublish = false
      wx.pageScrollTo({
        scrollTop: 0
      })
      this.setData({
        page: 1,
        isDone: false,
      })
      this.getInfo()
      this.getList(1)
    }
    this.getTime()
  },

  // 页面滚动事件
	onPageScroll(e) {
		this.setData({
			scrollTop: e?.scrollTop,
		})
	},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.refresh = true
    this.getInfo()
    this.setData({
      page: 1,
      isDone: false,
    })
    this.getList(1)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let { page, total } = this.data
    if (page < total) {
      page++
      this.setData({
        page
      })
      this.getList(page)
    } else {
      this.setData({
        isDone: true
      })
    }
  },

  /**
   * 获取列表
   * @param {*} page 当前页
   */
  async getList(page) {
    // this.setData({
    //   list: [],
    //   total: 0
    // })
    const { id, tabIndex } = this.data
    const res = await request.get(api.circlePostList, {
      page,
      size: 10,
      circleId: id,
      type: tabIndex
    }, { loading: false })
    const data = (res?.data?.records || []).map(item => {
      item.picUrls = (item?.picUrls || []).filter(Boolean)
      let picUrls = item.picUrls.slice(0, 3)
      return {
        ...item,
        picUrls,
        picMore: item?.picUrls?.length - picUrls.length
      }
    })
    this.setData({
      list: page === 1 ? data : [
        ...this.data.list,
        ...data,
      ],
      total: res?.data?.pages,
      totalSize: res?.data?.total,
    })
    this.refresh = false
    wx.stopPullDownRefresh()
  },
  // 获取详情数据
  async getInfo() {
    const { id,formShare } = this.data
    if (!id) return
    const res = await request.get(api.circleDetail, { id }, { loading: false })
    this.setData({
      info: {
        ...res?.data,
      }
    })
    if (!res?.data?.allow) {
      // 通过分享进入没权限 去圈子首页
      if(formShare){
        jump('circleHome')
        // wx.showModal({
        //   showCancel:false,
        //   title:'提示',
        //   content:'非私密圈子成员不能查看',
        //   success:(res)=>{
        //     if(res.confirm){
        //       jump('circleHome')
        //     }
        //   }
        // })
      }else{
        goBack()
      }
    }
  },
  // 通过分享进入验证登录
  checkIsLogin:function(){
    if (!app.isLogin()) {
      setStorage('redirectPath', '/pages/circleHome/circleHome')
      app.login()
      return true
    }else{
      return false
    }
  },
  // 加入&退出圈子
  async joinCircle(e) {
    let check = this.checkIsLogin()
    if(check) return

    const { id, info } = this.data
    if ([1, 7].includes(info.status)) {
      return
    }
    if (info.status === 5 && e !== false) {
      this.modal.show()
    } else {
      const res = await request.post((info.status !== 5 ? api.circleAdd : api.circleQuit) + '/' + id, null, { loading: false })
      if (res.httpStatus === 200) {
        setTimeout(() => {
          wx.showToast({
            icon: 'none',
            title: res.data,
          })
        })
      }
      this.getInfo()
      if (e === false) {
        this.modal.hide()
      }
    }
  },
   // 获取活动时间
   async getTime(){
    let res = await request.get(api.voteWaitTime,{},{ loading: false })
    if(res.httpStatus === 200){
      let startDate = res.data.startDate + ' ' + '00:00:00'
      let endDate = res.data.endDate + ' ' + '00:00:00'
      if((new Date().getTime() >= new Date(startDate.replace(/-/g, "/")).getTime()) && (new Date().getTime() < new Date(endDate.replace(/-/g, "/")).getTime())){
        this.setData({
          showTips: true
        })
      }else{
        this.setData({
          showTips: false
       })
      }
    }
  },  
  // 标签页选中变化
  tabChange(e) {
    const tabIndex = e?.currentTarget?.dataset?.index
    this.setData({
      tabIndex,
    })
    this.getList(1)
      wx.pageScrollTo({
        scrollTop: 0
      })
  },
  // 类型滑动开始
  typeTouchStart(event) {
    this.setData({
      typeScrollX: event?.touches?.[0]?.pageX || 0
    })
  },
  // 类型滑动移动
  typeTouchMove(event) {
    const { typeScrollX } = this.data
    const currentX = event?.touches?.[0]?.pageX || 0

    if (typeScrollX - currentX > 50) {
      console.log('右滑')
      this.touchType = 'right'
    } 
    if (currentX - typeScrollX > 50) {
      console.log('左滑')
      this.touchType = 'left'
    }
  },
  // 类型滑动结束
  typeTouchEnd() {
    if (!this.touchType) return
    const { info, tabIndex } = this.data
    const typeList = ['1', '2', '3', '4']
    // const typeList = info.status === 5 ? ['1', '2', '3', '4'] : ['1', '2', '4']
    const lastIndex = typeList.length - 1
    let currentIndex = typeList.indexOf(tabIndex)

    if (this.touchType === 'left') {
      currentIndex--
      currentIndex = currentIndex < 0 ? 0 : currentIndex
    }
    if (this.touchType === 'right') {
      currentIndex++
      currentIndex = currentIndex > lastIndex ? lastIndex : currentIndex
    }

    if (typeList[currentIndex] !== tabIndex && !this.refresh) {
      this.setData({
        tabIndex: typeList[currentIndex]
      })
      this.getList(1)
      wx.pageScrollTo({
        scrollTop: 0
      })
    }
    this.touchType = null
  },
  // 跳转到发帖页面
  jumpPost() {
    const { info } = this.data
    this.isFromPublish = true
    wx.navigateTo({
      url: `/pages/publish/publish?circleId=${info.id}`,
    })
  },
  // 跳转圈子设置页面
  jumpSetting() {
    const { info } = this.data
    jump('circleSet', {
      circleId: info.id
    })
  },
  // 跳转圈子成员页面
  jumpMember() {
    const { info } = this.data
    if (info.status === 5) {
      jump('circleMember', {
        circleId: info.id
      })
    }
  },
  // 打开描述弹窗
  showDescription(e) {
    if (e?.currentTarget?.dataset?.description) {
      this.setData({
        overflow: true
      })
      this.sheet.show()
    }
  },
  // 关闭描述弹窗
  hideDescription() {
    this.setData({
      overflow: false
    })
    this.sheet.hide()
  },
  // 确定退出圈子
  confirm() {
    this.joinCircle(false)
  },
  /**
   * 初始化加载动画
   */
  initAnimate() {
    if (this.inited) {
      return
    }
    wx.createSelectorQuery()
      .selectAll('#post-btn')
      .node((res) => {
        if(res[0]){
          const canvas = res[0].node
          const context = canvas.getContext('2d')
          canvas.width = 300
          canvas.height = 300
          lottie.setup(canvas)
          this.ani = lottie.loadAnimation({
            loop: true,
            autoplay: true,
            animationData: require('./data.js'),
            rendererSettings: {
              context,
            },
          })
          this.inited = true
        }
      })
      .exec()
  },
  // 用户点击右上角分享
  onShareAppMessage(e) {
    let { title } = this.data.info
    let { id } = this.data
    const userId = getStorage('userId') || ''
    let path = `/pages/circle/circle?id=${id}&formShare=true&inviteData=${userId}`
    return shareOptions('default', e, title, path, null)
  },
})